package com.jwd.avmanager.util;

import com.alibaba.fastjson.JSON;
import com.jwd.avmanager.parse.ProtocolParser;
import com.jwd.avmanager.pojo.Streams;
import com.jwd.avmanager.pojo.StreamsAddDate;
import com.jwd.avmanager.pojo.StreamsInfo;
import com.jwd.avmanager.server.ClientManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class HttpRequestUtils {
    static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
     // 发送GET请求
    public static String sendGetRequest(String url) throws IOException {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();
         try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("GET");
             reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
             String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
         return response.toString();
    }
     // 发送POST请求
    public static String sendPostRequest(String url, String data) throws IOException {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();
         try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
             byte[] postData = data.getBytes(StandardCharsets.UTF_8);
            connection.getOutputStream().write(postData);
             reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
             String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
         return response.toString();
    }

     public static List<String> SRSHttp (String url) throws IOException {
         String json = null;
        json = HttpRequestUtils.sendGetRequest(url);
         DebugLogger.info("SRSHttp-->"+json.toString());
         StreamsInfo streamsInfo = JSON.parseObject(json, StreamsInfo.class);
         List<String> lists = new ArrayList<>();
         List<Streams> streams = streamsInfo.getStreams();
         if (streams == null || streams.size() == 0){
             ClientManager.getInstance().clestreamsAddDateMap();
             return  null;
         } else {
             for (Streams stream : streams) {
                 StreamsAddDate streamsAddDate1 = ClientManager.getInstance().getstreamsAddDateMap(stream.getName());
                 //没有就添加
                 if(streamsAddDate1 == null){
                     StreamsAddDate streamsAddDate = new StreamsAddDate();
                     streamsAddDate.setStreams(stream);
                     streamsAddDate.setDate(new Date());
                     ClientManager.getInstance().addstreamsAddDateMap(stream.getName(),streamsAddDate);
                 } else {
                     Streams streams1 = streamsAddDate1.getStreams();
                    //b不相等重新添加
                     if( streams1.getClients() != stream.getClients() ){
                         StreamsAddDate streamsAddDate = new StreamsAddDate();
                         streamsAddDate.setStreams(stream);
                         streamsAddDate.setDate(new Date());
                         ClientManager.getInstance().addstreamsAddDateMap(stream.getName(),streamsAddDate);
                     }
                 }

             }
         }
         //缓存个数
         int size = ClientManager.getInstance().sizestreamsAddDateMap();
         DebugLogger.info(size+" 108");
         if(size != 0){
             ConcurrentHashMap<String, StreamsAddDate> map = ClientManager.getInstance().get();
             for (Map.Entry<String, StreamsAddDate> entry : map.entrySet()) {
                 DebugLogger.info(entry.getKey() + ":" + entry.getValue());
                 StreamsAddDate value = entry.getValue();
                 Streams streams1 = value.getStreams();
                 long s = JodaTimeUtil.timeDifference(value.getDate());
                 DebugLogger.debug(logger,s +" ----116---Clients-"+streams1.getClients()+"----URL---"+streams1.getUrl());
                 if(s>(15) && streams1.getClients()<=1){
                     ClientManager.getInstance().delstreamsAddDateMap(streams1.getName());
                     String url1 = streams1.getUrl();
                     boolean contains = url1.contains("/live/stream");
                     if(contains){
                         String replace = url1.replace("/live/stream", "");
                         DebugLogger.info(replace);

                         lists.add(replace);
                     }
                 }

             }
         }
         return lists;
     }
}